<template>
  <div class="change-password">
    <el-card class="change-password-card">
      <div slot="header" class="change-password-header">
        修改密码
      </div>
      <div class="change-password-form">
        <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="formData.oldPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="formData.newPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">修改密码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import api from '@/api/Password/changePassword'
export default {
  data() {
    return {
      formData: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.formData.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 执行密码修改操作
          api.changePassword(this.formData)
            .then(response => {
              this.$message.success('密码修改成功');
              this.formData={};
            })
            .catch(error => {
              if (error.response && error.response.code === 201) {
                this.$message.error('密码修改失败，原密码错误');
              }
            });
        }
      });
    }
  }
};
</script>

<style scoped>
.change-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.change-password-card {
  width: 400px;
}

.change-password-header {
  font-size: 18px;
  font-weight: bold;
}

.change-password-form {
  margin: 20px;
}
</style>
